package com.aliyun.heiyu.powermaster.server.rotary.dao.impl;

import com.aliyun.heiyu.common.util.JdbcUtil;
import com.aliyun.heiyu.powermaster.server.annotation.Transactional;
import com.aliyun.heiyu.powermaster.server.dao.entity.EmailPropertiesConfig;
import com.aliyun.heiyu.common.util.StringUtil;
import com.aliyun.heiyu.powermaster.server.rotary.contants.AirSqlContant;
import com.aliyun.heiyu.powermaster.server.rotary.dao.AirDAO;
import com.aliyun.heiyu.powermaster.server.rotary.enums.AirValueEnum;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.AirInformationDTO;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.AirTypeDTO;
import com.aliyun.heiyu.powermaster.server.rotary.object.entity.AiDataEntity;
import com.aliyun.heiyu.powermaster.server.rotary.object.transit.ResTem;
import com.aliyun.heiyu.powermaster.server.rotary.object.transit.TemData;
import com.aliyun.heiyu.powermaster.server.rotary.task.GetAirDataTask;
import com.aliyun.heiyu.powermaster.server.rotary.utils.IpcDataUtil;

import java.sql.SQLException;
import java.util.*;

/**
 * @Description 空调接口实现
 * @Author shun.zhang
 * @Date 2019/12/16 16:23
 **/

public class AirDAOImpl implements AirDAO {

    @Override
    public List<AirInformationDTO> getAirInformation(String airId, String pointKey) {
        return JdbcUtil.queryForList(AirSqlContant.GET_AIRINFORMATION, null, AirInformationDTO.class);
    }

    /**
     * @return Integer 保存的个数
     * @Author shun.zhang
     * @Description 保存数据
     * @Date 10:04 2019/12/17
     * @Param AiDataEntity aiDataEntity
     **/
    @Override
    public Integer saveTemp(AiDataEntity aiDataEntity) {
        if (null == aiDataEntity) {
            return null;
        }
        Object[] data = new Object[4];
        data[0] = aiDataEntity.getCurrentTemp();
        data[1] = aiDataEntity.getCollectTime();
        data[2] = aiDataEntity.getReferenceTemp();
        data[3] = aiDataEntity.getAirNumber();
        return JdbcUtil.insert(AirSqlContant.SAVEA_IRDATA, data);
    }

    /**
     * @return int 值
     * @Author shun.zhang
     * @Description 获取modbus的点位值
     * @Date 17:34 2019/12/17
     * @Param modbusType modbus类型
     * @Param modbusName modbus的名字
     **/
    @Override
    public int getModbusAddress(String modbusType, String modbusName) {
        if (StringUtil.isEmpty(modbusType) && StringUtil.isEmpty(modbusName)) {
            return -1;
        }
        Object[] kk = new Object[2];
        kk[0] = modbusType;
        kk[1] = modbusName;
        AirInformationDTO airInformationDTO = JdbcUtil.queryForBean(AirSqlContant.GET_MODBUSVALUE, kk, AirInformationDTO.class);
        return airInformationDTO.getVar_address();
    }

    /**
     * @param resTem
     * @param deviceId
     * @param modbusType
     * @param modbusMaps
     * @return Integer
     * @Description 保存空调动态数据
     **/
    @Override
    public Integer saveAirDataDynamic(ResTem resTem, String deviceId, String modbusType, Map<String, String> modbusMaps) {
        int count = 0;
        TemData temData = IpcDataUtil.getData(resTem.getData());
        Map<Integer, Double> data = temData.getValue();
        if (data.isEmpty()) {
            return null;
        }
        Object[] objects = new Object[data.size() + 2];
        StringBuilder params = new StringBuilder();
        StringBuilder values = new StringBuilder();
        StringBuilder sql = new StringBuilder();
        //拼接sql中的字段
        params.append("(device_id,collect_time,");
        //拼接值
        values.append("(?,?,");
        objects[count++] = deviceId;
        objects[count++] = GetAirDataTask.airDate;
        for (Integer key : data.keySet()) {
            if (key > 40) {
                continue;
            }
            //拼接map中的key
            StringBuilder paramKey = new StringBuilder();
            paramKey.append(modbusType)
                .append("_")
                .append(key);
            //获取字段
            String param = modbusMaps.get(paramKey.toString());
            //判断字段是否是未使用字段
            if (StringUtil.isEmpty(param) || AirValueEnum.NOT_USED.getKey().equals(param)) {
                continue;
            }
            //添加值
            objects[count++] = data.get(key);

            //判断字段
            params.append(param)
                .append(",");
            values.append("?,");
        }
        params.append(")");
        values.append(")");
        String pars = params.toString().replace(",)", ")");
        String vals = values.toString().replace(",)", ")");
        //拼接sql
        sql.append("insert into data_air_dynamic")
            .append(pars)
            .append(" values")
            .append(vals);
        /**移除object中最后未使用的位置*/
        int paramCount = data.size() - count + 2;
        if (paramCount != 0) {
            for (int i = 0; i < paramCount; i++) {
                objects = Arrays.copyOf(objects, objects.length - 1);
            }
        }
        return JdbcUtil.insert(sql.toString(), objects);
    }

    @Override
    public List<AirTypeDTO> getAirTypes() {
        return JdbcUtil.queryForList(AirSqlContant.AIR_TYPES, null, AirTypeDTO.class);
    }

    @Override
    public Map<String, String> getAirDynamic(String sn) {
        String sql = "select * FROM data_air_dynamic where device_id = ? order by id desc limit 1";
        Object[] obj = new Object[1];
        obj[0] = sn;
        return JdbcUtil.queryForMap(sql, obj);
    }

    /**
     * 通过主键查询空调信息
     *
     * @param sn
     * @return
     */
    @Override
    public AirInformationDTO getAirBySn(String sn) {
        String sql = "SELECT device_id from device_common where status = ? and `type`= 'air' and device_id = ?";
        Object[] obj = new Object[2];
        obj[0] = 1;
        obj[1] = sn;
        return JdbcUtil.queryForBean(sql, obj, AirInformationDTO.class);
    }

    @Override
    @Transactional
    public Boolean replaceInsert(Map<String, String> map, String bName) throws SQLException {
        //map不能为null
        StringBuilder sql=new StringBuilder();
        sql.append("REPLACE INTO "+bName+" ");
        List<String> list =new ArrayList<>();
        StringBuilder keys = new StringBuilder();
        StringBuilder values = new StringBuilder();
        keys.append("(");
        values.append("(");

        for(Map.Entry<String, String> vo : map.entrySet()){
            if(vo.getValue()==null || vo.getValue().equals("")){
                continue;
            }
            keys.append("`"+vo.getKey()+"`");
            keys.append(",");
            values.append("?");
            values.append(",");
            list.add(vo.getValue());
        }

        Object[] params=list.toArray();
        char[] str1=keys.substring(0, keys.length()-1).toCharArray();
        char[] str2=values.substring(0, values.length()-1).toCharArray();
        StringBuilder keyssb=new StringBuilder();
        StringBuilder valuessb=new StringBuilder();
        valuessb.append(str2);
        keyssb.append(str1);
        keys=keyssb;
        values=valuessb;
        keys.append(")");
        values.append(")");
        sql.append(keys).append("VALUES").append(values);

        boolean result =JdbcUtil.update(sql.toString(), params);
        return result;
    }

    @Override
    public EmailPropertiesConfig getEmailPropertiesConfig(String sn) {
        String sql = "SELECT `id`, `host`, `port`, `use_ssl`, `use_tls`, `username`, `pd_sender`, `sender`, `receiver` " +
            "  FROM email_properties_config where `id` = ?";
        Object[] obj = new Object[1];
        obj[0] = sn;
        return JdbcUtil.queryForBean(sql,obj, EmailPropertiesConfig.class);
    }

    /**
     * 获取空调最新动态数据
     *
     * @return
     */
    @Override
    public Map<String, String> getAirTemNew() {
        String sql = "select room_temperature from data_air_dynamic order by id desc limit 1";
        return JdbcUtil.queryForMap(sql,null);
    }

    /**
     * 获取最新的空调数据
     *
     * @return
     */
    @Override
    public Map<String, String> getAirNew() {
        String sql = "select air.air_set_temperature_lower_limit,air.air_set_temperature_upper_limit from device_common com left  join device_air air on com.device_id = air.device_id where com.status = 1 and com.type='air' order by com.modified_time desc limit 1";
        return JdbcUtil.queryForMap(sql,null);
    }
}
